from flask import abort, jsonify
from flask import current_app
from flask import render_template
# from werkzeug import item
from flask import session

from info.models import News,User
from info.response_code import RET
from . import news_blue


# 新闻详情展示(用户)
# 请求路径: /news/<int:news_id>
# 请求方式: GET
# 请求参数:news_id
# 返回值: detail.html页面, 用户data字典数据


@news_blue.route('/<int:news_id>')
def news_info(news_id):
    # 获取session中的用户信息
    user_id = session.get("user_id")
    # 查询用户对象
    user = None
    if user_id:
        try:
            user = User.query.get(user_id)
        except Exception as e:
            current_app.logger.error(e)



    #  根据新闻编号查询新闻对象
    news =  None
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)



#     判断新闻对象是否存在
    if not news:
        abort(404)

    # 查询前6条热门新闻
    try:
        click_news = News.query.order_by(News.clicks.desc()).limit(6).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="获取新闻失败")

    # 将新闻对象列表,转成字典列表
    click_news_list = []
    for item in click_news:
        click_news_list.append(item.to_dict())


    # 拼接数据渲染页面
    data = {
        "news_info":news.to_dict(),
        "click_news_list":click_news_list,
        "user_info": user.to_dict() if user else ""
    }


    return render_template("news/detail.html",data=data)




